import { createStore } from 'vuex'
import SocketService from '@/api/websocket';
import Router from "@/router";
import { getUser } from '@/api/server_login'
import { setAutoCheckData } from '@/utils/autoCheck';
import { getConfig,getAutoCheckList } from '@/api/server_inspection'
import Bus from "@/utils/eventBus"
const store = createStore({
  state: {
    user:{},
    serviceTime:parseInt(String(+new Date()/1000)),
    menuName:'cockpit',
    csrf:'',
  },
  getters: {
    serviceTime(state){
      return state.serviceTime
    },
    CSRF(state){
      return state.csrf
    }
  },
  mutations: {
    SET_USER (state, payload) {
        state.user = payload
    },
    SET_CSRF (state, payload) {
        state.csrf = payload
    },
    SET_MENU_NAME (state, payload) {
        state.menuName = payload
    },
    SET_TIME (state, payload) {
        state.serviceTime = payload
    }
  },
  actions: {
    async getAppConfig (context, num) {
      let res = await getConfig({})
      let serviceTime = res.serviceTime
      context.commit('SET_CSRF', res._zc_csrf)
      setInterval(()=>{
        serviceTime ++ 
        context.commit('SET_TIME', serviceTime)
        Bus.$emit('serverTime',serviceTime)
      },1000)
      setInterval(() => {
        Bus.$emit('detectionIntervalTime')
      }, res.detectionIntervalTime * 1000 || 10000)
      context.dispatch('getAllAutoCheckList')
      return res
    },
    async getUser (context, num) {
      if(!window.localStorage.getItem('token')){
        setTimeout(()=>{
          Router.push({name:'login'})
        },500)
        return
      }
      let {userInfo} = await getUser()
      context.commit('SET_USER', userInfo)  // 通过context去触发mutions中的sum
      SocketService.Instance.send({
        type:'init',
        userId:userInfo.user_id,
      })
    },
    async getAllAutoCheckList (context, num) {
      let res = await getAutoCheckList({});
      if (res.result == "success") {
        let list = res.autoCheckList || []
        setAutoCheckData(list,context.state.serviceTime)
      }
    },
  },
  modules: {}
})
export default store